package com.useeinfo.oa.open.Infrastructure.Interceptor;

import com.useeinfo.oa.common.annotations.LoggerAnnotations;
import com.useeinfo.oa.modules.logger.annotations.ActiveLogs;
import com.useeinfo.oa.modules.logger.annotations.LoginLogs;
import com.useeinfo.oa.modules.logger.biz.ActiveLogBiz;
import com.useeinfo.oa.modules.logger.biz.LoginLogBiz;
import com.useeinfo.oa.modules.logger.entity.ActiveLog;
import com.useeinfo.oa.modules.logger.entity.LoginLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by chjoy on 17/9/26.
 */
 public class LogCheckInteceptor extends HandlerInterceptorAdapter {

//	@Autowired
//	private SystemLogInfoBiz systemLogInfoBiz;

	@Autowired
	private ActiveLogBiz activeLogBiz;

	@Autowired
	private LoginLogBiz loginLogBiz;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		HandlerMethod methodHandler = (HandlerMethod) handler;
		LoggerAnnotations loggerAnnotations = methodHandler.getMethodAnnotation(LoggerAnnotations.class);

		//如果方法中添加了@LoggerAnnotations 这里的auth不为null
		//如果@LoggerAnnotations(check=false) 这里的auth为false,即不用进行拦截验证，@AuthCheckAnnotation默认为前面定义的true　　
		//if (loggerAnnotations == null) {
		//	return true;
		//} else if (!loggerAnnotations.check()) {
		//	return true;
		//}

		ActiveLogs activeLogs = methodHandler.getMethodAnnotation(ActiveLogs.class);
		LoginLogs loginLogs = methodHandler.getMethodAnnotation(LoginLogs.class);
		if (activeLogs == null && loginLogs == null) {
			return true;
		}

		if(activeLogs != null && activeLogs.check()){
			//log.info(activeLogs.name());
			//log.info(activeLogs.remark());
			//log.info(activeLogs.type());
			//log.info(request.getRemoteAddr());

			ActiveLog activeLog = new ActiveLog();
			activeLog.setActiveRemark(activeLogs.remark());
			activeLog.setIp(request.getRemoteAddr());
			activeLog.setName(request.getRemoteUser());
			activeLogBiz.save(activeLog);
		}

		if(loginLogs != null && loginLogs.check()){
			LoginLog loginLog = new LoginLog();
			loginLog.setIp(request.getRemoteAddr());
			loginLog.setType((loginLogs.type()));
			loginLog.setCreateDate(new Date());
			loginLog.setName(request.getRemoteUser());
			loginLogBiz.save(loginLog);
		}
		return true;
	}
}
